package com.tyl.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

@Configuration
//aop横切式拦阻器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/").permitAll()//所有人都可以访问
                .antMatchers("/level1/**").hasRole("vip1")//指定人访问
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限的时候默认跳到登录页
        //开启登录页
        http.formLogin().loginPage("/toLogin");

        //开启注销,注销后会到某个页面
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能
        http.rememberMe();
    }

    // @Autowired
    // private DataSource dataSource;
    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 从内存中读取认证
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())//BCryptPasswordEncoder 密码编码，高版本不设置加密会报错
                .withUser("tyl").password(new BCryptPasswordEncoder().encode("199969")).roles("vip1")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("199969")).roles("vip1","vip2","vip3")
                .and()
                .withUser("hxy").password(new BCryptPasswordEncoder().encode("199969")).roles("vip2","vip3");

        // //从数据库中读取认证
        // auth.jdbcAuthentication().passwordEncoder(new BCryptPasswordEncoder())
        //         .dataSource(dataSource).withDefaultSchema()
        //         .withUser("root")
        //         .password(new BCryptPasswordEncoder().encode("199969"))
        //         .roles("vip1","vip2","vip3");
    }
}
